package com.wanxi.action;

import com.wanxi.util.Tool;

import java.io.*;
import java.util.Scanner;

public class UserLogin {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入用户名");
        String user = scanner.next();
        System.out.println("请输入密码");
        String pass = scanner.next();

        UserInfo userInfo = getTxtUser();
//        先去查看cookie.txt里面是否由数据，
//        如果有，则直接通过里面的信息进行登录，
//        否则，查看userinfo.txt里面的信息
        if (userInfo.getUsername().equals(user) && userInfo.getPassword().equals(pass)) {
            System.out.println("登录成功");
            saveCookieTxt(userInfo);
        } else {
            System.out.println("登录失败");
        }
    }

    private static void saveCookieTxt(UserInfo userInfo) {
        String path = "E:\\wanxi\\step-2\\java02-0921\\day21OtherIOStream\\src\\com\\wanxi\\action";
        String fileName = "cookie.txt";
        OutputStream outputStream = Tool.getFileOutputStream(path, fileName);
        try {
            outputStream.write(("username=" + userInfo.getUsername()).getBytes());
            outputStream.write("\n".getBytes());
            outputStream.write(("password=" + userInfo.getPassword()).getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    private static UserInfo getTxtUser() {
        String path = "E:\\wanxi\\step-2\\java02-0921\\day21OtherIOStream\\src\\com\\wanxi\\action";
        String fileName = "userinfo.txt";
        Reader reader = new InputStreamReader(Tool.getInputStream(path, fileName));
        BufferedReader inputStreamReader = new BufferedReader(reader);
        UserInfo userInfo = new UserInfo();
        try {
            String result = inputStreamReader.readLine();
            String[] results = result.split("&");
            String user = results[0];
            String pass = results[1];
            userInfo.setUsername(user.split("=")[1]);
            userInfo.setPassword(pass.split("=")[1]);
            System.out.println(userInfo);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return userInfo;
    }
}
